//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_triger_api_serv

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/triger_dao"
	"atomgit.com/openlinksaas-org/api-server/utils"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_triger_api"
)

func (apiImpl *ProjectTrigerApiImpl) ListMsg(ctx context.Context, req *project_triger_api.ListMsgRequest) (*project_triger_api.ListMsgResponse, error) {
	emptyList := []*project_triger_api.TrigerMsgInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_triger_api.ListMsgResponse{
			Code:    project_triger_api.ListMsgResponse_CODE_WRONG_SESSION,
			ErrMsg:  "会话不存在",
			MsgList: emptyList,
		}, nil
	}
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_triger_api.ListMsgResponse{
			Code:    project_triger_api.ListMsgResponse_CODE_NO_PROJECT,
			ErrMsg:  "项目不存在",
			MsgList: emptyList,
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_triger_api.ListMsgResponse{
			Code:    project_triger_api.ListMsgResponse_CODE_NO_PERMISSION,
			ErrMsg:  "没有权限",
			MsgList: emptyList,
		}, nil
	} else if err != nil {
		return nil, err
	}

	count, err := triger_dao.MsgIndexDao.Count(ctx, req.TrigerId, req.FilterByAttr, req.AttrList)
	if err != nil {
		return nil, err
	}
	msgIndexItemList, err := triger_dao.MsgIndexDao.List(ctx, req.TrigerId, req.FilterByAttr, req.AttrList, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	//列出内容
	recorcIdList := []string{}
	for _, msgIndexItem := range msgIndexItemList {
		recorcIdList = append(recorcIdList, msgIndexItem.RecordId)
	}
	contentItemList, err := triger_dao.MsgContentDao.ListById(ctx, recorcIdList)
	if err != nil {
		return nil, err
	}
	contentItemMap := map[string][]byte{}
	for _, contentItem := range contentItemList {
		contentItemMap[contentItem.RecordId] = []byte(contentItem.Content)
	}
	//生成结果
	msgList := []*project_triger_api.TrigerMsgInfo{}
	for _, msgIndexItem := range msgIndexItemList {
		content := contentItemMap[msgIndexItem.RecordId]
		if content == nil {
			content = []byte{}
		}
		msg := &project_triger_api.TrigerMsgInfo{
			MsgId:     msgIndexItem.MsgId,
			TrigerId:  msgIndexItem.TrigerId,
			TimeStamp: msgIndexItem.TimeStamp,
			AttrList:  msgIndexItem.AttrList,
			Content:   content,
		}
		msgList = append(msgList, msg)
	}

	return &project_triger_api.ListMsgResponse{
		Code:       project_triger_api.ListMsgResponse_CODE_OK,
		TotalCount: count,
		MsgList:    msgList,
	}, nil
}
